<template>
  <el-card>
    <el-row>
      <el-form ref="queryFormRef" :model="queryParams" :inline="true" class="demo-form-inline">
        <el-form-item label="昵称" prop="nickName">
          <el-input v-model="queryParams.nickName" placeholder="昵称" clearable ></el-input>
        </el-form-item>
        <el-form-item label="号码" prop="phonenumber">
          <el-input v-model="queryParams.phonenumber" placeholder="号码" clearable ></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="全部" clearable>
            <el-option label="正常" value="0" />
            <el-option label="停用" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handlerSearch">搜索</el-button>
          <el-button type="primary" @click="openDialog('user-form', '')">添加用户</el-button>
        </el-form-item>
      </el-form>
    </el-row>
    <el-table :data="tableData" style="width: 100%" :border="true">
      <el-table-column prop="userName" label="用户账号" align="center" width="100" />
      <el-table-column prop="nickName" label="用户昵称" align="center" width="150"/>
      <el-table-column prop="phonenumber" label="用户号码" align="center" width="120"/>
      <el-table-column prop="sex" label="性别" align="center" width="100">
        <template #default="scope">
          {{ scope.row.status == 0 ? "男" : "女" }}
        </template>
      </el-table-column>
      <el-table-column prop="email" label="邮箱" align="center" width="200"/>
      <el-table-column prop="status" label="账号状态" align="center" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status == 0 ? 'success' : 'info'">{{
            scope.row.status == 0 ? "正常" : "停用"
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" align="center" width="180" />
      <el-table-column prop="loginDate" label="最后登录时间" align="center" width="180"/>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">
            编辑
          </el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        v-model:current-page="currentPage"
        :page-size="10"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="total, prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
  </el-card>

  <!-- 弹窗 -->
  <el-dialog
    v-model="dialog.visible"
    :title="dialog.title"
    :width="dialog.width"
    append-to-body
    @close="closeDialog"
  >
    <!-- 用户新增/编辑表单 -->
    <el-form
      v-if="dialog.type === 'user-form'"
      ref="userFormRef"
      :model="formData"
      :rules="rules"
      label-width="80px"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="formData.username" placeholder="请输入用户名"/>
      </el-form-item>

      <el-form-item label="用户昵称" prop="nickname">
        <el-input v-model="formData.nickname" placeholder="请输入用户昵称" />
      </el-form-item>

      <el-form-item label="所属部门" prop="deptId">
        <el-tree-select
          v-model="formData.deptId"
          placeholder="请选择所属部门"
          :data="deptList"
          filterable
          check-strictly
          :render-after-expand="false"
        />
      </el-form-item>

      <el-form-item label="性别" prop="sex">
        <el-radio-group v-model="formData.sex">
          <el-radio :value="0">男</el-radio>
          <el-radio :value="1">女</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="角色" prop="roleId">
        <el-select v-model="formData.roleId" placeholder="请选择">
          <el-option
            v-for="item in roleList"
            :key="item.roleId"
            :label="item.roleName"
            :value="item.roleId"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="手机号码" prop="phonenumber">
        <el-input v-model="formData.phonenumber" placeholder="请输入手机号码" maxlength="11" />
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input v-model="formData.email" placeholder="请输入邮箱" maxlength="50"/>
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio :value="0">正常</el-radio>
          <el-radio :value="1">停用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <!-- 弹窗底部操作按钮 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSubmit(userFormRef)">确 定</el-button>
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref,reactive,onMounted } from 'vue'
import {Search} from '@element-plus/icons-vue'
import {querySysUser,addOrEditSysUser,delSysUserByUserId,getSysUserInfo} from '@/api/SysUser'
import {getSysDeptTree} from '@/api/SysDept'
import {getSysRoleList} from '@/api/SysRole'
import { ElMessage,ElMessageBox } from 'element-plus'

const currentPage = ref(1)
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
const total = ref(1)
const queryFormRef = ref(); // 查询表单
const userFormRef = ref(); // 用户表单
const tableData = ref([]) // 用户列表数据
const deptList = ref([]) // 部门下拉数据源
const roleList = ref([]) // 角色下拉数据源

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  nickName: '',
  phonenumber: '',
  status: '',
});

// 弹窗对象
const dialog = reactive({
  visible: false,
  type: "user-form",
  width: 600,
  title: "",
});

// 用户表单数据
const formData = reactive({
  id: '',
  status: 0,
  username: '',
  nickname: '',
  deptId: '',
  sex: 0,
  roleId: '',
  phonenumber: '',
  email: ''
});

// 校验规则
const rules = reactive({
  username: [{ required: true, message: "用户名不能为空", trigger: "blur" }],
  nickname: [{ required: true, message: "用户昵称不能为空", trigger: "blur" }],
  deptId: [{ required: true, message: "所属部门不能为空", trigger: "blur" }],
  roleId: [{ required: true, message: "用户角色不能为空", trigger: "blur" }],
  email: [
    {
      pattern: /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/,
      message: "请输入正确的邮箱地址",
      trigger: "blur",
    },
  ],
  phonenumber: [
    {
      pattern: /^1\d{10}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
});

// 用户信息列表
const getSysUserData = () => {
  querySysUser(queryParams).then(res => {
    tableData.value = res.records
    total.value = res.total
  })
}

// 搜索
const handlerSearch = () => {
  getSysUserData()
}

// 编辑用户
const handleEdit = (index, row) => {
  openDialog('user-form',row.userId)
}

// 删除用户
const handleDelete = (index, row) => {
  console.log(index, row)
  ElMessageBox.confirm(
    '是否删除该用户数据？',
    '删除',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(() => {
    delSysUserByUserId(row.userId).then((res) =>{
      getSysUserData()
      ElMessage.success('删除成功')
    }).catch(error => {
      ElMessage.error('获取信息失败')
    })
  })
  .catch(() => {})
}

const handleCurrentChange = (val) => {
  queryParams.pageNum = val 
  getSysUserData()
};
const handleSizeChange = (val) => {
  console.log("handleSelectionChange", val);
}

// 部门数据
const deptData = ()=>{
  getSysDeptTree().then(res => {
    const data = res.map((r) => {
      let d = {
        value: r.deptId,
        label: r.deptName,
        children: setChildren(r.children)
      }
      return d
    })
    deptList.value = data
  })
}
// 部门数据递归回显
function setChildren(children) {
  if (!children || children.length === 0) {
      return [];
  }
  return children.map((child) => {
      let d = {
        value: child.deptId,
        label: child.deptName,
        children: setChildren(child.children)
      }
      return d;
  });
}

// 角色数据
const roleData = ()=>{
  getSysRoleList().then(res => {
    roleList.value = res
  })
}

// 弹窗新增/编辑用户
const openDialog = (type, userId) => {
  dialog.visible = true;
  dialog.type = type;
  deptData()
  roleData()
  if (dialog.type === "user-form") {
    if (userId) {
      dialog.title = "修改用户";
      var data = {
        userId: userId
      }
      getSysUserInfo(data).then((res) =>{
        formData.userId = res.userId
        formData.status = parseInt(res.status)
        formData.username = res.userName
        formData.nickname = res.nickName
        formData.sex = parseInt(res.sex)
        formData.deptId = res.deptId
        formData.roleId = res.roleId
        formData.phonenumber = res.phonenumber
        formData.email = res.email
      }).catch(error => {
        ElMessage.error('获取信息失败')
      })
    } else {
      dialog.title = "新增用户";
    }
  }
}

// 保存用户信息
const handleSubmit = (from) => {
  if (dialog.type === "user-form") {
    from.validate((valid) => {
      if (valid) {
        console.log('formData=',formData)
        addOrEditSysUser(formData).then(r => {
          closeDialog()
          getSysUserData()
          ElMessage.success('保存成功')
        }).catch(e =>{
          ElMessage.success('保存失败')
        })
      } else {
        ElMessage.error('请填写数据')
      }
    })
  }
}

// 关闭窗口
const closeDialog = () => {
  dialog.visible = false;
  if (dialog.type === "user-form") {
    userFormRef.value.resetFields();
    userFormRef.value.clearValidate();

    formData.id = undefined;
    formData.status = 1;
  }
}

onMounted(() =>{
  getSysUserData()
})
</script>

<style lang="scss" scoped>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}

</style>
